import {
  getToken, 
  getH5Token, 
  setToken, 
  setH5Token, 
  removeToken, 
  setUserId, 
  setApplication, 
  removeUserId, 
  removeApplication, 
  getUserId,
  getH5UserId,
  setH5UserId, 
  setH5Application,
  setH5Username,
  setH5Name,
  removeH5Name,
  removeH5Username,
  removeH5Token, 
  removeH5UserId, 
  removeH5Application, 
  setH5Id, 
  removeH5Id,
  getH5Id
} from '@/config/cookie'
import {defineStore} from "pinia"
import {doGet, doPost} from "@/config/http"
import {isNullOrUndefinedOrEmpty, svc} from "@/config/common"

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getH5Id() ? getToken() : getH5Token(),
      name: '',
      username: '',
      avatar: '',
      avatarImg: '',
      sign: '',
      signImg: '',
      roles: [],
      permissions: [],
      organization: {
        id: null,
        organizationType: null,
        organizationCode: null,
        organizationName: null,
        state: null,
      },
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        return new Promise((resolve, reject) => {
          const data = {
            username,
            password,
            code,
            uuid,
          }
          return doPost(svc, '/custom/login', data).then(res => {
            console.debug('login', res)
            setToken(res['username'])
            setUserId(res['userId'])
            setApplication()
            this.token = res['username']
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // h5登录
      h5Login(userInfo) { 
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        return new Promise((resolve, reject) => {
          const data = {
            username,
            password,
            code,
            uuid
          }
          return doPost(svc, '/custom/login', data).then(res => {
            console.log('login res-！！！！>', res);
            setH5Token(res['username'])
            setH5UserId(res['userId'])
            setH5Application()
            setH5Id(res['userId'])
            setH5Username(res['username'])
            setH5Name(res['name'])
            console.log('aaa',res['username'])
            this.name = res['name']
            this.username = res['username']
            this.token = res['username']
            resolve()
          }).catch(error => {
            console.error("login error=>",error)
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          let userId = getUserId()
          return doGet(svc, `/custom/getUserProfile/${userId}`, null).then(async res => {
            console.debug('getUserProfile',res)
            const user = res
            this.organization = res.dept
            const empty = ''
            this.avatarImg = empty
            this.signImg = empty
            if (user['avatar']) {
              let r = await doGet(svc, `/customAttachment/preview/${user.avatar}`, null, false)
              if (isNullOrUndefinedOrEmpty(r)) {
                r = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
              }
              let img = 'data:image/gif;base64,' + r
              this.avatar = user['avatar'];
              this.avatarImg = img;
            }
            if (user['sign']) {
              let r = await doGet(svc, `/customAttachment/preview/${user.sign}`, null, false)
              if (isNullOrUndefinedOrEmpty(r)) {
                r = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
              }
              let img = 'data:image/gif;base64,' + r
              this.sign = user['sign'];
              this.signImg = img;
            }
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.name = res['name']
            this.username = res['username']
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取H5用户信息
      getH5Info() {
        return new Promise((resolve, reject) => {
          let userId = getH5UserId()
          return doGet(svc, `/custom/getUserProfile/${userId}`, null).then(async res => {
            console.debug('getUserProfile',res)
            const user = res
            this.organization = res.dept
            const empty = ''
            this.avatarImg = empty
            this.signImg = empty
            if (user['avatar']) {
              let r = await doGet(svc, `/customAttachment/preview/${user.avatar}`, null, false)
              if (isNullOrUndefinedOrEmpty(r)) {
                r = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
              }
              let img = 'data:image/gif;base64,' + r
              this.avatar = user['avatar'];
              this.avatarImg = img;
            }
            if (user['sign']) {
              let r = await doGet(svc, `/customAttachment/preview/${user.sign}`, null, false)
              if (isNullOrUndefinedOrEmpty(r)) {
                r = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
              }
              let img = 'data:image/gif;base64,' + r
              this.sign = user['sign'];
              this.signImg = img;
            }
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.name = res['name']
            this.username = res['username']
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logout() {
        return new Promise((resolve, reject) => {
          let res = {
          }
          this.token = ''
          this.roles = []
          this.permissions = []
          removeToken()
          removeUserId()
          removeApplication()
          resolve()
          sessionStorage.clear()
        })
      },
      // 退出h5系统
      h5Logout() {
        return new Promise((resolve, reject) => {
          let res = {
          }
          this.token = ''
          this.roles = []
          this.permissions = []
          removeH5Token()
          removeH5UserId()
          removeH5Application()
          removeH5Id()
          resolve()
          removeH5Name()
          removeH5Username()
          sessionStorage.clear()
        })
      },
    }
  })

export default useUserStore
